import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import { saveUserInfo, getUserInfo } from '../utils/auth';
import styles from './Emaillogin.module.css';
import  {http,host,port} from '../utils/host'
const Emaillogin: React.FC = () => {
    const navigate = useNavigate();
    const [email, setEmail] = useState('');
    const [verificationCode, setVerificationCode] = useState('');
    const [isPasswordMode, setIsPasswordMode] = useState(false);
    const [password, setPassword] = useState('');
    const [agreedToPrivacy, setAgreedToPrivacy] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [isLoading, setIsLoading] = useState(false);
    const [isVerificationLoading, setIsVerificationLoading] = useState(false);
    const [hasBoundEmail, setHasBoundEmail] = useState(false);
    const [boundEmail, setBoundEmail] = useState('');

    // 检查用户是否已绑定邮箱
    useEffect(() => {
        const userEmail = localStorage.getItem('userEmail');
        const userInfo = getUserInfo();
        
        if (userEmail && userInfo) {
            setHasBoundEmail(true);
            setBoundEmail(userEmail);
            setEmail(userEmail); // 自动填入绑定的邮箱
        } else {
            setHasBoundEmail(false);
        }
    }, []);

    // 验证邮箱格式
    const validateEmail = (email: string) => {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    };

    // 获取验证码
    const handleGetVerificationCode = async () => {
        if (!hasBoundEmail) {
            Toast.show({
                content: '请先绑定邮箱',
                position: 'center',
            });
            return;
        }

        if (!validateEmail(email)) {
            Toast.show({
                content: '请输入正确的邮箱地址',
                position: 'center',
            });
            return;
        }

        if (!agreedToPrivacy) {
            Toast.show({
                content: '请先同意用户隐私政策',
                position: 'center',
            });
            return;
        }

        try {
            setIsVerificationLoading(true);
            
            const response = await axios.post(`${http}${host}${port}/send-qq-code`, {
                email: email
            });

            if (response.data.code === 0) {
                Toast.show({
                    content: '验证码已发送到您的邮箱',
                    position: 'center',
                });

                // 开始倒计时
                setCountdown(60);
                const timer = setInterval(() => {
                    setCountdown(prev => {
                        if (prev <= 1) {
                            clearInterval(timer);
                            return 0;
                        }
                        return prev - 1;
                    });
                }, 1000);
            } else {
                Toast.show({
                    content: response.data.msg || '发送验证码失败',
                    position: 'center',
                });
            }
        } catch (error: any) {
            console.error('发送验证码错误:', error);
            Toast.show({
                content: '发送验证码失败，请重试',
                position: 'center',
            });
        } finally {
            setIsVerificationLoading(false);
        }
    };

    // 登录处理
    const handleLogin = async () => {
        if (!hasBoundEmail) {
            Toast.show({
                content: '请先绑定邮箱',
                position: 'center',
            });
            return;
        }

        if (!validateEmail(email)) {
            Toast.show({
                content: '请输入正确的邮箱地址',
                position: 'center',
            });
            return;
        }

        if (isPasswordMode) {
            if (!password) {
                Toast.show({
                    content: '请输入密码',
                    position: 'center',
                });
                return;
            }
        } else {
            if (!verificationCode) {
                Toast.show({
                    content: '请输入验证码',
                    position: 'center',
                });
                return;
            }
        }

        if (!agreedToPrivacy) {
            Toast.show({
                content: '请先同意用户隐私政策',
                position: 'center',
            });
            return;
        }

        try {
            setIsLoading(true);
            
            if (isPasswordMode) {
                // 邮箱密码登录（暂时模拟）
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                Toast.show({
                    content: '邮箱密码登录功能开发中',
                    position: 'center',
                });
            } else {
                // 验证码登录
                const response = await axios.post(`${http}${host}${port}/verify-qq-code`, {
                    email: email,
                    code: verificationCode,
                    username: email.split('@')[0] // 使用邮箱前缀作为用户名
                });

                if (response.data.code === 0) {
                    // 获取原有的用户信息
                    const existingUserInfo = getUserInfo();
                    if (existingUserInfo) {
                        // 使用原有的用户信息，保持与学号登录一致
                        saveUserInfo(existingUserInfo);
                        
                        Toast.show({
                            content: '登录成功',
                            position: 'center',
                        });

                        // 登录成功后跳转
                        navigate('/layout/home');
                    } else {
                        Toast.show({
                            content: '用户信息获取失败，请重新登录',
                            position: 'center',
                        });
                    }
                } else {
                    Toast.show({
                        content: response.data.msg || '验证码错误',
                        position: 'center',
                    });
                }
            }

        } catch (error: any) {
            console.error('登录错误:', error);
            
            let errorMessage = '登录失败，请重试';
            if (error.code === 'ERR_NETWORK') {
                errorMessage = '网络连接失败，请检查后端服务是否启动';
            } else if (error.response?.data?.msg) {
                errorMessage = error.response.data.msg;
            } else if (error.response?.status === 404) {
                errorMessage = '登录接口不存在，请检查后端服务';
            } else if (error.response?.status === 500) {
                errorMessage = '服务器内部错误';
            }
            
            Toast.show({
                content: errorMessage,
                position: 'center',
            });
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className={styles['email-login-container']}>
            {/* 背景装饰元素 */}
            <div className={styles['background-decoration']} />
            <div className={styles['background-decoration-2']} />

            {/* 主要内容区域 */}
            <div className={styles['main-content']}>
                {/* 返回按钮 */}
                <div className={styles['back-button']} onClick={() => navigate('/login')}>
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M19 12H5"/>
                        <path d="M12 19l-7-7 7-7"/>
                    </svg>
                </div>

                {/* 标题区域 */}
                <div className={styles['title-section']}>
                    <h1 className={styles['welcome-title']}>邮箱登录</h1>
                    <p className={styles['subtitle']}>使用邮箱验证码快速登录</p>
                </div>

                {/* 表单区域 */}
                <div className={styles['form-section']}>
                    {/* 邮箱输入 */}
                    <div className={styles['input-group']}>
                        <input
                            type="email"
                            className={styles['input-field']}
                            placeholder={hasBoundEmail ? "已绑定邮箱" : "请先绑定邮箱"}
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            disabled={!hasBoundEmail}
                        />
                        {!hasBoundEmail && (
                            <div className={styles['bind-email-tip']}>
                                <span>请先在个人中心绑定邮箱</span>
                                <button 
                                    className={styles['bind-email-button']}
                                    onClick={() => navigate('/myprivacy')}
                                >
                                    去绑定
                                </button>
                            </div>
                        )}
                    </div>

                    {/* 验证码或密码输入 */}
                    {isPasswordMode ? (
                        <div className={styles['input-group']}>
                            <input
                                type="password"
                                className={styles['input-field']}
                                placeholder="输入密码"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                            />
                        </div>
                    ) : (
                        <div className={styles['input-group']}>
                            <input
                                type="text"
                                className={styles['input-field']}
                                placeholder="输入验证码"
                                value={verificationCode}
                                onChange={(e) => setVerificationCode(e.target.value)}
                                maxLength={6}
                            />
                        </div>
                    )}

                    {/* 获取验证码按钮 */}
                    {!isPasswordMode && hasBoundEmail && (
                        <button
                            className={styles['verification-button']}
                            onClick={handleGetVerificationCode}
                            disabled={countdown > 0 || isVerificationLoading}
                        >
                            {countdown > 0 ? `${countdown}s后重发` : (isVerificationLoading ? '发送中...' : '获取邮箱验证码')}
                        </button>
                    )}

                    {/* 隐私政策 */}
                    <div className={styles['privacy-section']}>
                        <input
                            type="checkbox"
                            className={styles['privacy-checkbox']}
                            checked={agreedToPrivacy}
                            onChange={(e) => setAgreedToPrivacy(e.target.checked)}
                        />
                        <span>我已阅读并同意</span>
                        <a href="#" className={styles['privacy-link']}>
                            《用户隐私政策》
                        </a>
                    </div>

                    {/* 登录按钮 */}
                    <button
                        className={styles['login-button']}
                        onClick={handleLogin}
                        disabled={isLoading || !hasBoundEmail}
                    >
                        {isLoading ? '登录中...' : (hasBoundEmail ? '登录' : '请先绑定邮箱')}
                    </button>

                    {/* 密码登录链接 */}
                    <div className={styles['password-login']}>
                        <a
                            href="#"
                            className={styles['password-login-link']}
                            onClick={(e) => {
                                e.preventDefault();
                                setIsPasswordMode(!isPasswordMode);
                                setVerificationCode('');
                                setPassword('');
                            }}
                        >
                            {isPasswordMode ? '验证码登录' : '密码登录'}
                        </a>
                    </div>

                    {/* 注册链接 */}
                    <div className={styles['password-login']}>
                        <span style={{ color: '#666', fontSize: '14px' }}>还没有账号？</span>
                        <a
                            href="#"
                            className={styles['password-login-link']}
                            onClick={(e) => {
                                e.preventDefault();
                                navigate('/register');
                            }}
                        >
                            立即注册
                        </a>
                    </div>
                </div>

                {/* 分割线 */}
                <div className={styles['divider']}>
                    <span>其他登录方式</span>
                </div>

                {/* 其他登录方式 */}
                <div className={styles['other-login-methods']}>
                    <button
                        className={styles['other-login-button']}
                        onClick={() => navigate('/login')}
                    >
                        📱 手机号登录
                    </button>
                    <button
                        className={styles['other-login-button']}
                        onClick={() => navigate('/register')}
                    >
                        👤 学号登录
                    </button>
                </div>
            </div>
        </div>
    );
};

export default Emaillogin;